﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;

namespace Web
{


    /// <summary>
    /// 自定义策略提供
    /// </summary>
    public class AbpAuthorizationPolicyProvider : IAuthorizationPolicyProvider
    {

        // 程序集 Nito.AsyncEx.Coordination,
        //  private static readonly AsyncLock _mutex = new();
        private readonly AuthorizationOptions _authorizationOptions;
        private DefaultAuthorizationPolicyProvider BackupPolicyProvider { get; }

        public AbpAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
        {
            BackupPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
            _authorizationOptions = options.Value;
        }


        public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
        {
            return BackupPolicyProvider.GetDefaultPolicyAsync();
        }

        public async Task<AuthorizationPolicy> GetFallbackPolicyAsync()
        {
            return  await BackupPolicyProvider.GetFallbackPolicyAsync();
        }

        public async Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            if (policyName is null) throw new ArgumentNullException(nameof(policyName));

            var policy = await BackupPolicyProvider.GetPolicyAsync(policyName);
            if (policy is not null)
            {
                return policy;
            }

            //using (await _mutex.LockAsync())
            //{

            //}


            var builder = new AuthorizationPolicyBuilder();
            builder.AddRequirements(new PermissionRequirement(policyName));
            policy = builder.Build();
            _authorizationOptions.AddPolicy(policyName, policy);

            return policy;
        }

    }
}
